//
//  AddUserVC.m
//  AILock
//
//  Created by 谭亚明 on 2020/7/15.
//  Copyright © 2020 tym. All rights reserved.
//

#import "AddUserVC.h"
#import "OpenlimitsVC.h"
#import "UIimage+Extends.h"
#import "UserService.h"
#import "UIView+ZFFrame.h"
#import "UserModel.h"
#import "YPVideoPickerViewController.h"
#import "HXPhotoViewController.h"
#import "HXPhotoView.h"
#import "UIButton+Gradient.h"
#import "FamilyModel.h"
#import "EquipmentModel.h"
#import "FamilyService.h"
#import "SeleFamilyUserVC.h"

@interface AddUserVC ()<HXPhotoViewControllerDelegate>

@property(nonatomic,strong) EquipmentModel *equipModel;
@property(nonatomic,strong) FamilyService *services;

@property(nonatomic,weak) IBOutlet UIImageView *headImage;
@property(nonatomic,copy) NSString *headImageUrl;
@property(nonatomic,weak) IBOutlet UITextField  *nameLab;

@property(nonatomic,weak) IBOutlet UIButton *nextBtn;

@property (strong, nonatomic) HXPhotoManager *manager;//相册manager
@end

@implementation AddUserVC

-(instancetype)initWithEquipMent:(EquipmentModel*)model{
    self = [super init];
    self.equipModel = model;
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addBackBtnFunc];
    [self addTitle:@"添加用户"];
    
    self.nextBtn.layer.masksToBounds = YES;
    self.nextBtn.layer.cornerRadius = 5;
    self.headImage.layer.cornerRadius = self.headImage.zf_width/2;
    self.headImage.layer.masksToBounds = YES;
    
    [self.nameLab addTarget:self action:@selector(changedTextField:) forControlEvents:UIControlEventEditingChanged];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forBarMetrics:UIBarMetricsDefault];
}

#pragma mark - 懒加载选择视频的manager
- (HXPhotoManager *)manager {
    if (!_manager) {
        _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypeVideo];
        _manager.configuration.albumShowMode = HXPhotoAlbumShowModePopup;
        _manager.configuration.openCamera = NO;
        _manager.configuration.videoMaxNum = 1;
        _manager.configuration.maxNum = 1;
        _manager.configuration.photoCanEdit = NO;
        _manager.configuration.hideOriginalBtn = YES;
        _manager.configuration.videoCanEdit = NO;
        _manager.configuration.replacePhotoEditViewController = NO;
        _manager.configuration.replaceVideoEditViewController = NO;
        _manager.configuration.showBottomPhotoDetail = NO;
        _manager.configuration.themeColor = [UIColor blackColor];
        _manager.configuration.navBarBackgroudColor = [UIColor blackColor];
        _manager.configuration.navigationTitleColor = [UIColor whiteColor];
        _manager.configuration.selectVideoLimitSize = YES;
        _manager.configuration.limitVideoSize = 1024*1024*100;
        _manager.configuration.photoStyle = HXPhotoStyleDark;
        _manager.configuration.cellDarkSelectBgColor = rgba(76, 132, 255);
        _manager.configuration.languageType = HXPhotoLanguageTypeSc;
        _manager.configuration.reverseDate = YES;
        _manager.configuration.videoMaximumSelectDuration = 60;
    }
    return _manager;
}

-(void)changedTextField:(UITextField*)fid{
    if ( self.nameLab.text.length<1) {
        [self.nextBtn setBackgroundImage:[UIImage imageWithColor:rgba(230, 230, 230) withSize:self.nextBtn.bounds.size] forState:UIControlStateNormal];
    }else{
        [self.nextBtn gradientButtonWithSize:CGSizeMake(300, 44) colorArray:@[(id)rgba(139, 175, 255),(id)rgba(76, 132, 255)] percentageArray:@[@(0.5),@(1)] gradientType:GradientFromLeftTopToRightBottom];
    }
}


-(FamilyService*)services{
    if (_services == nil) {
        _services = [[FamilyService alloc] init];
    }
    return _services;
}

//绑定家庭成员
-(IBAction)bangdingAction:(id)sender{
    
    SeleFamilyUserVC *userVC = [[SeleFamilyUserVC alloc] initEquipmentModel:self.equipModel];
    [self.navigationController pushViewController:userVC animated:YES];
}

-(IBAction)nextAction:(id)sender{
    
    if (!self.nameLab.text.length) {
        [WHToast showMessage:@"请输入用户昵称" duration:2 finishHandler:nil];
        return;
    }
    [self.services getAddequipmentgroupuser:[UserTool getCurrentFamily].familyId nickname:self.nameLab.text
      heakImaUrl:self.headImageUrl
                                equipmentID:self.equipModel.equipmentId
                                 Completion:^(LMJBaseResponse * _Nonnull responsed) {
        
        if (!responsed.message) {
            OpenlimitsVC *limitsVC = [[OpenlimitsVC alloc] initWithUserId:[responsed.responseObject[@"data"] integerValue] equipMent:_equipModel];
            [self.navigationController pushViewController:limitsVC animated:YES];
        }else{
            [WHToast showMessage:responsed.message duration:2 finishHandler:nil];
        }
    }];
}

//选择图片
-(IBAction)seleImageAction:(id)sender{
    
    self.manager.type  = HXPhotoManagerSelectedTypePhoto;
    self.manager.configuration.openCamera = YES;
    YPVideoPickerViewController *vc = [[YPVideoPickerViewController alloc] init];
     vc.manager = self.manager;
     vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - HXPhotoViewController delegate
- (void)photoViewController:(HXPhotoViewController *)photoViewController
didDoneAllList:(NSArray<HXPhotoModel *> *)allList
        photos:(NSArray<HXPhotoModel *> *)photoList
        videos:(NSArray<HXPhotoModel *> *)videoList
                   original:(BOOL)original{
    if (photoList.count > 0) {
       HXPhotoModel *photoModel = photoList.firstObject;
        self.headImage.image = photoModel.thumbPhoto;
        [self personalUploadHeadImgInterfaceWithImage:photoModel.thumbPhoto];
    }
}

- (void)personalUploadHeadImgInterfaceWithImage:(UIImage *)uploadImage  {
    //网络请求管理器
    TYMWeak(self);
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    NSString *requestUrlStr = [NSString stringWithFormat:@"%@%@", BaseUrl,  urlImageUpload];
    [sessionManager POST:requestUrlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *imageData = UIImageJPEGRepresentation(uploadImage, 1);
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@%@.jpg", [UserTool getLogInUser].token, str];
        [formData appendPartWithFileData:imageData name:@"file"  fileName:fileName mimeType:@"image/jpg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (![responseObject[@"code"] integerValue]) {
            weakself.headImageUrl = responseObject[@"data"];
            //[self uploadPhone:responseObject[@"data"]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [WHToast showMessage:@"上传图片失败" duration:2 finishHandler:nil];
    }];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
